import React, {Component} from 'react'
import {
  View,
  Text,
  StyleSheet,
  Dimensions,
  Platform,
  TouchableOpacity,
  ActivityIndicator
} from 'react-native'
import {Actions} from "react-native-router-flux";
import ICON from 'react-native-vector-icons/Ionicons'
import * as stringUtils from './../../utils/srting'
import Toast2, {
  DURATION
} from 'react-native-easy-toast'
import {Toast, Overlay} from 'teaset'
import * as ShareMenu from './../common/ShareMenu'

// 引入sdk
import RNAlibcSdk, {AlibcTradeWebView} from 'react-native-alibc-sdk';
import { SafeAreaView } from 'react-navigation';

const {
  height: deviceHeight,
  width: deviceWidth
} = Dimensions.get("window");


class TaobaoWebScene extends Component{
  constructor(props){
    super(props)
    this.state = {
      webLoading: true,
      openUrl:'',
      like: false
    }
    this._onTradeResult.bind(this)
    this._onWebViewStateChange = this._onWebViewStateChange.bind(this);
  }

  componentDidMount() {
    this.startTime = Date.parse(new Date()) / 1000
    this.props.actions.getGoodsInfo(this.props.auctionId)
    this.props.actions.getUserLike(this.props.auctionId)

  }

  componentWillReceiveProps(nextProps) {
    const {goodsInfo, userLike, postCollect} = nextProps
    if(this.props.goodsInfo !== goodsInfo){

      if (goodsInfo.error !== false) {
        if (goodsInfo.error.status === 401) {
          Actions.login()
          return;
        }

        this.toast.show(goodsInfo.error.message)
        Actions.pop()
      }else{
        if (goodsInfo.isLoading) {

        }else{
          if (goodsInfo.data) {
            this.setState({openUrl:goodsInfo.data.openUrl})
          }
        }
      }

    }


    if(this.props.userLike !== userLike){
      if (userLike.error !== false) {
        if (userLike.error.status === 401) {
          this.setState({like: false})
        }

      }else{
        if (userLike.isLoading) {

        }else{
          this.setState({like: true})
        }
      }
    }


    if(this.props.postCollect !== postCollect){
      if (postCollect.error !== false) {
        if (postCollect.error.status === 401) {
          Actions.login()
          return;
        }

        this.toast.show(postCollect.error.message)

      }else{
        if (postCollect.isLoading) {

        }else{
          Toast.success(postCollect.data)
          this.setState({like: true})
        }
      }
    }

  }


  componentWillUnmount() {
    let startTime = this.startTime
    let endTime = Date.parse(new Date()) / 1000
    this.props.actions.postUserHistory({...this.props, startTime, endTime})
  }



  _onTradeResult(result){
    console.log(result);
  }

  _onWebViewStateChange(state) {
    console.log(state);
    if(state.loading){
      this.setWebLoading(true)
    }else{
      this.setWebLoading(false)
    }
  }

  //打开/隐藏Loading
  setWebLoading(status){
    this.setState({webLoading: status})
  }


  renderContent(){
    const {
      isLoading,
      data,
      error
    } = this.props.goodsInfo

    if(isLoading){
      return(
        <View style={{flex:1, justifyContent:'center', alignItems:'center'}}>
          <ActivityIndicator
            animating={true}
            size='large'
          />
        </View>
      )
    }

    if(data && !isLoading){
      return(
        <AlibcTradeWebView
          style={styles.webView}
          ref="MyWebView"
          param={
            {type: "url", payload: data.openUrl}
          }
          onTradeResult={this._onTradeResult}
          onStateChange={this._onWebViewStateChange}
        />
      )
    }
  }


  renderShare(){
    if(global.isWXAppInstalled){
      return(
        <TouchableOpacity
          onPress={()=>{
            Overlay.show(ShareMenu.ShareMenu({
              'cate': 'good',
              'title': stringUtils.delHtmlTag(this.props.title),
              'description': '领优惠券+返利+推荐返佣，真心比双11还便宜！',
              'thumbImage': this.props.pictUrl,
              'webpageUrl': 'https://tao.vyxjj.com/#/goods?id='+this.props.auctionId
            }))
          }}
          style={{height:40,width:40,justifyContent:'center', paddingRight:10, alignItems:'center'}}>
          <ICON name='md-share' size={20}  color='#000' />
        </TouchableOpacity>
      )
    }else{
      return(
        <View></View>
      )
    }
  }

  renderStar(){
    if(global.isWXAppInstalled){
      return(
        <TouchableOpacity
          onPress={()=>{
            this.props.actions.postUserCollect({...this.props})
          }}
          style={{height:40,width:25,justifyContent:'center', paddingRight:5, alignItems:'center'}}>
          {this.state.like ?
            <ICON name='ios-star' size={20} color='#f00'/>
            : <ICON name='ios-star' size={20} />
          }

        </TouchableOpacity>
      )
    }else{
      return(
        <View></View>
      )
    }
  }

  render(){
    return(
      <SafeAreaView style={styles.container}>
        <View style={styles.title}>
          <TouchableOpacity
            onPress={()=>{Actions.pop()}}
            style={{height:40, width:40,justifyContent:'center', paddingLeft:10
            }}>
            <ICON name='ios-arrow-back' size={26}  color='#000'/>
          </TouchableOpacity>
          <Text style={{color:'#000', width:245, fontSize:15}}  numberOfLines={1}>{stringUtils.delHtmlTag(this.props.title)}</Text>

          {this.renderStar()}
          {this.renderShare()}

        </View>
        {this.renderContent()}
        <Toast2
          ref={view => this.toast = view}
          style={{backgroundColor:'red'}}
          opacity={0.6}
          position='top'/>
      </SafeAreaView>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor:'#fff'
  },
  title:{
    height: 40,
    justifyContent:'space-between',
    alignItems:'center',
    borderBottomWidth:1,
    borderBottomColor:'#f6f6f6',
    flexDirection:'row',
  },
  webView: {
    flex:1
  },
})

export const LayoutComponent = TaobaoWebScene

export function mapStateToProps(state, props) {
  return {
    routes: state.routes,
    goodsInfo: state.goodsInfoReducer,
    userLike: state.userLikeReducer,
    postCollect: state.postUserCollectReducer,
    postHistory: state.postUserHistoryReducer
  }
}